package keter.framework.web.security.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import keter.framework.web.security.crypto.Des;
import keter.framework.web.security.crypto.RSAUtils;
import keter.framework.web.util.RequestUtil;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class KeterUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter{
	/**
	* Logger for this class
	*/
	private static final Logger logger = LoggerFactory.getLogger(KeterUsernamePasswordAuthenticationFilter.class);
            
    public Authentication attemptAuthentication(HttpServletRequest request,
            HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }

        String auth_token = request.getParameter("authenticate_token");
//        String plain_token = Des.strDec(auth_token, "haha", "hehe", "caonima");
        String plain_token = RSAUtils.decryptStringByJs(auth_token);
        String username = StringUtils.substringBefore(plain_token, "|");
        String password = StringUtils.substringAfter(plain_token, "|");

        if (username == null) {
            username = "";
        }

        if (password == null) {
            password = "";
        }

        username = username.trim();

        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                username, password);

        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }

//    private JSONObject parseJson(HttpServletRequest request) {
//        JSONObject json = new JSONObject();
//        try {
//            json = (JSONObject) JSON.parse(RequestUtil.getJson(request));
//        } catch (Exception e) {
//            //该filter产生的异常不会被KeterExceptionResolver拦截
//            logger.error("json解析失败");
//        }
//        return json;
//    }    
//    
   
}
